// 下载 具体的小说章节
let axios = require("axios")
let cheerio = require("cheerio")

require("./connect.js")

let {
    Book
} = require("./mod/bookcover.js")
let {
    Chapter
} = require("./mod/chapter.js")


// 获取具体的章节内容
async function getchapters() {
    // 从 book表中取出arr
    let booklists = await Book.find()

    for (let i = 0; i < booklists.length; i++) {
        let book_title=booklists[i].book_title
        for (let j = 0; j < booklists[i].url_arr.length; j++) {
            // console.log(booklists[i].url_arr[j])
            let url=booklists[i].url_arr[j]["chapter_url"]
            let chapter_title=booklists[i].url_arr[j]["chapter_title"]
            let res = await axios.get(url)
            let $ = cheerio.load(res.data)
            let chapter_content = $("#content").html().trim()
            chapter_title = book_title + "___" + chapter_title

            // 保存章节信息
            try {
            new Chapter({
                chapter_content,
                chapter_title,
                book_title
            }).save()   
            } catch{
                console.log('章节保存失败')
            }

        }
    }
    // console.log(booklists)
}


getchapters()